<script setup>
import NavBar from "@/components/common/navbar/NavBar.vue";
import {computed, onMounted, reactive, toRefs} from "vue";
import {useRouter} from "vue-router";
import {showLoadingToast, showNotify} from "vant";
import {checkedCart, deleteCartItem, getCart, modifyCart} from "@/network/cart";
import {useStore} from "vuex";

// 数据模型状态
const state = reactive({
	list: [],
	result: [], // id数组
	checkAll: true
})
const {list, result, checkAll} = toRefs(state);
const router = useRouter()
const store = useStore()
// 初始化购物车数据
const init = () => {
	showLoadingToast({
		message: '加载中...',
		forbidClick: true
	});
	getCart('include=goods').then(res => {
		state.list = res.data
		state.result = res.data.filter(item => item['is_checked'] === 1).map(item => item.id)
	})
}
// 异步改变购物车数量
const onChange = (value, detail) => {
	showLoadingToast({
		message: '加载中...',
		forbidClick: true
	});
	modifyCart(detail.name, {num: value}).then(() => {
		// 将本地list修改
		state.list.forEach(item => {
			if (item.id === detail.name) {
				item.num = value;
			}
		})
	})
}

// 前往购物
const goTo = () => {
	router.push({path: '/'})
}
// 复选框改变处理
const groupChange = (result) => {
	// 判断是否全选
	state.checkAll = result.length === state.list.length && result.length !== 0;
	state.result = result;
	// 改变数据库选中状态
	checkedCart({cart_ids: result});
}
// 全选按钮
const allCheck = () => {
	if (!state.checkAll) {
		state.result = state.list.map(item => item.id);
		state.checkAll = true;
	} else {
		state.result = [];
		state.checkAll = false;
	}
}
// 删除按钮
const deleteGood = (id) => {
	deleteCartItem(id).then(() => {
		init()
		store.dispatch('updateCart')
	})
}
// 计算总价
const total = computed(() => {
	// 总价变量
	let sum = 0;
	state.list.filter(item => [...state.result].includes(item.id)).forEach(item => sum += parseInt(item['num']) * parseFloat(item['goods'].price))
	return sum
})
// 创建订单
const onSubmit = () => {
	// 判断用户是否选择了商品
	if (state.result.length === 0) {
		showNotify({type: 'danger', message: '请选择商品！'});
	} else {
		// 跳转到订单页面（暂无）
		router.push({path: '/createorder', query: {cart_ids: state.result}})
	}
}
// 初始化数据
onMounted(() => {
	init();
})
</script>

<template>
	<div>
		<nav-bar class="nav-bar">
			<template v-slot:default>
				购物车
			</template>
		</nav-bar>
		<div class="cart-box">
			<div class="cart-body">
				<van-checkbox-group ref="checkboxGroup" v-model="result" @change="groupChange">
					<van-swipe-cell v-for="(item,index) in list" :key="index" :right-width="50">
						<div class="good-item">
							<van-checkbox :name="item.id"/>
							<div class="good-img"><img :src="item.goods.cover_url" alt=""></div>
							<div class="good-desc">
								<div class="good-title">
									<span>{{ item.goods.title }}</span>
									<span>库存:{{ item.goods['stock'] }}</span>
								</div>
								<div class="good-btn">
									<div class="price"><small>¥</small>{{ item.goods.price.toFixed(2) }}</div>
									<van-stepper :max="item.goods['stock']" :model-value="item.num" :name="item.id" async-change integer min="1" @change="onChange"/>
								</div>
							</div>
						</div>
						<template #right>
							<van-button
								class="delete-button"
								icon="delete"
								square
								type="danger"
								@click="deleteGood(item.id)"
							/>
						</template>
					</van-swipe-cell>

				</van-checkbox-group>
			</div>
			<van-submit-bar :price="total*100" button-text="生成订单" class="submit-all" @submit="onSubmit">
				<van-checkbox :checked="checkAll" @click="allCheck">全选</van-checkbox>
			</van-submit-bar>

			<div v-if="!list.length" class="empty">
				<img alt="空购物车" class="empty-cart" src="@/assets/images/empty-car.png">
				<div class="title">购物车空空如也</div>
				<van-button block color="#1baeae" round type="primary" @click="goTo">前往选购</van-button>
			</div>

		</div>

	</div>
</template>

<style lang="scss" scoped>
.cart-box {
	.cart-body {
		margin: 60px 0 100px 0;
		padding-left: 10px;

		.good-item {
			display: flex;

			.good-img {
				img {
					width: 100px;
					height: auto;
				}
			}

			.good-desc {
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				flex: 1;
				padding: 20px;

				.good-title {
					display: flex;
					justify-content: space-between;
				}

				.good-btn {
					display: flex;
					justify-content: space-between;

					.price {
						font-size: 16px;
						color: red;
						line-height: 28px;
					}

					.van-icon-delete {
						font-size: 20px;
						margin-top: 4px;
					}
				}
			}
		}

		.delete-button {
			width: 50px;
			height: 100%;
		}
	}

	.empty {
		width: 50%;
		text-align: center;
		margin: 25vh auto 0;

		.empty-cart {
			width: 150px;
			margin-bottom: 20px;
		}

		.van-icon-smile-o {
			font-size: 50px;
		}

		.title {
			font-size: 16px;
			margin-bottom: 20px;
		}
	}

	.submit-all {
		margin-bottom: 55px;

		.van-checkbox {
			margin-left: 0;
		}

		.van-submit-bar__text {
			margin-right: 10px
		}

		.van-submit-bar__button {
			background: red;
		}
	}

	.van-checkbox__icon--checked .van-icon {
		background-color: red;
		border-color: red;
	}
}
</style>